package miiteen.customsportal.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.net.URLEncoder;

public class HttpUtil {
    /**
     * 下载文件
     *
     * @param fileName
     * @param bytes
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> download(String fileName, byte[] bytes) throws IOException {

        if (fileName.length() > 150) {
            fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
        } else {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
        //设置请求头内容,告诉浏览器代开下载窗口
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    }
}
